package com.zybzzz.workapp.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zybzzz.workapp.R;
import com.zybzzz.workapp.activity.PlanMsgActivity;
import com.zybzzz.workapp.entry.PlanMsg;
import com.zybzzz.workapp.entry.PlanMsgLab;

import java.util.Collections;
import java.util.List;

public class PlanMsgListFragment extends Fragment {

    //RecyclerView中放置ViewHolder，来展示一个个计划
    private RecyclerView planMsgRecyclerView;
    //PlanMsgAdapter给RecyclerView分配足够的ViewHolder，让RecyclerView充满ViewHolder
    private PlanMsgAdapter adapter;



    /**
     * 在该Fragment被创建时调用，属于Fragment的生命周期函数
     * @param: [inflater, container, savedInstanceState]
     * @return: android.view.View
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_planmsg_list,container,false);

        planMsgRecyclerView=(RecyclerView) view.findViewById(R.id.planmsg_recycler_view);
        planMsgRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        //更新UI组件，函数实现在下面
        updateUI();
        return view;
    }


    /**
     * 在更改信息后更新组件，也属于fragment的生命周期函数
     * @param: []
     * @return: void
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    //定义适配器和视图容器的内部类
    //PlanMsgHolder继承RecyclerView.ViewHolder表示它是视图容器
    //实现View.OnClickListener表示它是一个监听器，简单设置过后点击PlanMsgHolder就会相应单击事件
    private class PlanMsgHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        //封装信息的类，即模型model
        private PlanMsg planMsg;

        //这些都是视图view
        //计划的标题
        private TextView titleTextView;
        //计划的备注
        private TextView remarkTextView;
        //计划是否完成的图片显示，根据计划完成与否会显示图片变化，该功能暂时还没实现
        //private ImageView finishStatusView;
        //计划进度条
        private ProgressBar progressBar;
        //分子
        private TextView finishedNumView;
        //分母
        private TextView totalNumView;


        /**
         * PlanMsgHolder的构造方法
         * @param: [inflater, parent]
         * @return:
         * @author: ZhangYiBo
         * @date: 2020/10/15
         */
        public PlanMsgHolder(LayoutInflater inflater,ViewGroup parent){
            super(inflater.inflate(R.layout.list_item_planmsg,parent,false));
//            此处可能出现id拼错的错误
            //在原先设计的layout中找到相关的组件
            titleTextView=(TextView) itemView.findViewById(R.id.planmsg_title);
            remarkTextView=(TextView) itemView.findViewById(R.id.planmsg_remark);
            //finishStatusView=(ImageView) itemView.findViewById(R.id.finish_status_img);
            progressBar=(ProgressBar) itemView.findViewById(R.id.progressBar);
            finishedNumView=(TextView) itemView.findViewById(R.id.textView5);
            totalNumView=(TextView) itemView.findViewById(R.id.textView6);

            //对ViewHolder设置监听，这样它就可以响应单击事件了
            itemView.setOnClickListener(this);
            //打印到日志
            Log.d("PlanMsgListFragment.PlanMsgHolder","oncreate");
        }


        /**
         * 用来绑定视图和模型的方法
         * @param: [planMsg]
         * @return: void
         * @author: ZhangYiBo
         * @date: 2020/10/15
         */
        public void bind(PlanMsg planMsg){
            //此处实现绑定视图和模型
            this.planMsg=planMsg;
            titleTextView.setText(planMsg.getTitle());
            remarkTextView.setText(planMsg.getRemark());
            //此处实现图片根据完成情况变化 （暂时没有调试过，后续引入时间调试）
            //finishStatusView.setImageResource(planMsg.getIsfinished()? R.drawable.finish : R.drawable.unfinish);
            progressBar.setMax(planMsg.getTaskTotalNum());
            progressBar.setProgress(planMsg.getNumberOfFinish());
            finishedNumView.setText(String.valueOf(planMsg.getTaskTotalNum()));
            totalNumView.setText(String.valueOf(planMsg.getNumberOfFinish()));
        }


        /**
         * 实现onClick方法，这样经过构造方法中的设置之后，PlanMsgHolder就可以响应单击事件
         * @param: [v]
         * @return: void
         * @author: ZhangYiBo
         * @date: 2020/10/15
         */
        @Override
        public void onClick(View v) {
            Log.e("PlanMsgListFragment.click","in click method");
            Intent intent= PlanMsgActivity.makeNewIntentByPlanId(getActivity(),planMsg.getId());
            startActivity(intent);
        }
    }


    //适配器内部类 用于给RecyclerView分配足够的ViewHolder
    private class PlanMsgAdapter extends RecyclerView.Adapter<PlanMsgHolder>{

        //List<PlanMsg>存储PlanMsg，大量的PlanMsg即将被展示到页面
        private final List<PlanMsg> planMsgs;
        //这是一个触屏滑动帮助类，帮助在RecyclerView中实现滑动展示的效果
        private ItemTouchHelper itemTouchHelper;


        /**
         * 适配器的构造函数，在构造函数中绑定数据源，并且实现ItemTouchHelper
         * @param: [planMsgs]
         * @return:
         * @author: ZhangYiBo
         * @date: 2020/10/15
         */
        public PlanMsgAdapter(final List<PlanMsg> planMsgs){
            this.planMsgs=planMsgs;
            itemTouchHelper=new ItemTouchHelper(new ItemTouchHelper.Callback() {

                /**
                 * 该函数规定处理和滑动的方向，RecyclerView只能上下滑动
                 * @param: [recyclerView, viewHolder]
                 * @return: int
                 * @author: ZhangYiBo
                 * @date: 2020/10/15
                 */
                @Override
                public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                    Log.e("moveplanmodule", "getMovementFlags()");
                    if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                                ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                        final int swipeFlags = 0;
                        return makeMovementFlags(dragFlags, swipeFlags);
                    } else {
                        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                        final int swipeFlags = 0;
                        return makeMovementFlags(dragFlags, swipeFlags);
                    }
                }


                /**
                 * 规定滑动时调用的回调函数，返回值一定要是true，否则无效
                 * 主要实现滑动时容器中的PlanMsg的位置交换
                 * @param: [recyclerView, viewHolder, target]
                 * @return: boolean
                 * @author: ZhangYiBo
                 * @date: 2020/10/15
                 */
                @Override
                public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                    Log.e("moveplanmodule", "onMove()");
                    //得到当拖拽的viewHolder的Position
                    int fromPosition = viewHolder.getAdapterPosition();
                    //拿到当前拖拽到的item的viewHolder
                    int toPosition = target.getAdapterPosition();
                    if (fromPosition < toPosition) {
                        for (int i = fromPosition; i < toPosition; i++) {
                            Collections.swap(planMsgs, i, i + 1);
                        }
                    } else {
                        for (int i = fromPosition; i > toPosition; i--) {
                            Collections.swap(planMsgs, i, i - 1);
                        }
                    }
                    PlanMsgAdapter.this.notifyItemMoved(fromPosition, toPosition);
                    return true;
                }


                /**
                 * 删除的时候才调用的方法 仅仅在规定可以左右滑动的时候再调用
                 * @param: [viewHolder, direction]
                 * @return: void
                 * @author: ZhangYiBo
                 * @date: 2020/10/15
                 */
                @Override
                public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                    Log.e("moveplanmodule", "onSwiped()");
                }


                /**
                 * 从静止状态变成其他状态的时候调用这个方法
                 * @param: [viewHolder, actionState]
                 * @return: void
                 * @author: ZhangYiBo
                 * @date: 2020/10/15
                 */
                @Override
                public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
                    super.onSelectedChanged(viewHolder, actionState);
                    Log.e("moveplanmodule", "onSelectedChanged()");
                    if (actionState != ItemTouchHelper.ACTION_STATE_IDLE)
                        viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
                }


                /**
                 * 移动什么都完成的时候调用这个方法
                 * @param: [recyclerView, viewHolder]
                 * @return: void
                 * @author: ZhangYiBo
                 * @date: 2020/10/15
                 */
                @Override
                public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                    super.clearView(recyclerView, viewHolder);
                    Log.e("moveplanmodule", "clearView()");
                    viewHolder.itemView.setBackgroundColor(0);
                }


                /**
                 * 是否通过长按再进行操作
                 * @param: []
                 * @return: boolean
                 * @author: ZhangYiBo
                 * @date: 2020/10/15
                 */
                @Override
                public boolean isLongPressDragEnabled() {
                    Log.e("moveplanmodule", "isLongPressDragEnabled()");
                    return false;
                }
            });//此处可能有标点的错误


            //将itemTouchHelper绑定至planMsgRecyclerView
            itemTouchHelper.attachToRecyclerView(PlanMsgListFragment.this.planMsgRecyclerView);
        }


        /**
         * 创建ViewHolder
         * @param: [parent, viewType]
         * @return: com.zybzzz.workapp.fragment.PlanMsgListFragment.PlanMsgHolder
         * @author: ZhangYiBo
         * @date: 2020/10/15
         */
        @NonNull
        @Override
        public PlanMsgHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater=LayoutInflater.from(getActivity());
            return new PlanMsgHolder(layoutInflater,parent);
        }


        /**
         * 完成绑定
         * @param: [holder, position]
         * @return: void
         * @author: ZhangYiBo
         * @date: 2020/10/15
         */
        @Override
        public void onBindViewHolder(@NonNull final PlanMsgHolder holder, final int position) {

            PlanMsg planMsg=planMsgs.get(position);
            holder.titleTextView.setOnLongClickListener(new View.OnLongClickListener() {
                /**
                 * 这里可以设置从那个位置开始计划可以拖动
                 * 直接设置从0位置开始，即任何位置都可以拖动
                 * @param: [v]
                 * @return: boolean
                 * @author: ZhangYiBo
                 * @date: 2020/10/15
                 */
                @Override
                public boolean onLongClick(View v) {
                    if (position >= 0) {
                        PlanMsgAdapter.this.itemTouchHelper.startDrag(holder);
                    }

                    return false;
                }
            });
            holder.bind(planMsg);
        }


        /**
         * 返回适配器中的计划个数
         * @param: []
         * @return: int
         * @author: ZhangYiBo
         * @date: 2020/10/15
         */
        @Override
        public int getItemCount() {
            return planMsgs.size();
        }
    }

    /**
     * 该函数用于更新界面上的视图显示
     * @param: []
     * @return: void
     * @author: ZhangYiBo
     * @date: 2020/10/15
     */
    private void updateUI(){
        PlanMsgLab planMsgLab=PlanMsgLab.get(getActivity());
        //获取到最新的List<PlanMsg>计划容器，并将容器中计划更新到页面
        List<PlanMsg> planMsgs=planMsgLab.getPlanMsgs();
        planMsgRecyclerView.addItemDecoration(new SpaceItemDecoration(3));
        Log.e("updateUI", "更新获取的列表");
        if (adapter==null){
            adapter=new PlanMsgAdapter(planMsgs);
            planMsgRecyclerView.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }
    }



}
